<?php

namespace app\services\ad\monitor;

use app\datalog\AdMonitorLog;
use app\model\sdk\log\LogAdMonitor;
use app\model\sdk\log\LogAdMonitorInfo;
use support\Request;

// Uc-微信小程序
// 对接文档
// https://www.yuque.com/chaojihuichuan/hhcp03/cu861b
class UcXyx extends MonitorBase
{

    // 解析callback_url里的uctrackid
    public function parseUctrackid($callback_url)
    {
        $url = urldecode($callback_url);
        parse_str(parse_url($url, PHP_URL_QUERY), $query_arr);

        return $query_arr['uctrackid'] ?? '';
    }

    // 此接口由子类继承
    // 处理落地监控数据
    public function handleMonitorInfo(Request $request)
    {
        // 待匹配日志
        $params       = $request->all();
        $callback_url = $params['callback_url'];
        $click_id     = $this->parseUctrackid($callback_url);

        $log              = LogAdMonitor::suffix(date('Ym'));
        $log->create_time = time();
        $log->plan_id     = $params['plan_id'];
        $log->ip          = $params['ip'] ?? '';
        $log->click_id    = md5($click_id);
        $log->save();

        // 完整日志
        $info              = LogAdMonitorInfo::suffix(date('Ym'));
        $info->create_time = time();
        $info->plan_id     = $params['plan_id'];
        $info->monitor_id  = $log->id;
        $info->data        = json_encode($params, JSON_UNESCAPED_UNICODE);
        $info->save();

        // 落地日志
        AdMonitorLog::getInstance()->addLog($log, $info);

        return yqok();
    }
}
